/**
 * @Author yinyunqi
 * @date 2017年12月30日
 * @Content 
 */
package com.yongqi.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.yongqi.model.Family;
import com.yongqi.model.Menu;
import com.yongqi.model.back.Email;
import com.yongqi.model.back.Message;
import com.yongqi.pub.PrincipalFormat;
import com.yongqi.pub.ValidateCode;
import com.yongqi.service.FamilyService;
import com.yongqi.service.MenuService;
import com.yongqi.service.back.EmailService;
import com.yongqi.service.back.MessageService;
import com.yongqi.shiro.UsernamePasswordUsertypeToken;

@Controller
public class HomeController {
    @Autowired
    FamilyService familyService;
    @Autowired
    MenuService menuService;
    @Autowired
    MessageService messageService;
    @Autowired
    EmailService emailService;
    
    @RequestMapping("/loginValidate")
    @ResponseBody
    public String loginValidate(HttpServletRequest request) throws Exception {
	String familyAccount = request.getParameter("username");
	String password = request.getParameter("password");
//	String randomcode = request.getParameter("randomcode");
//	String verifyCode = (String) request.getSession().getAttribute("verifyCode");
	//通过familyAccount获取usertype(level)
	Family family = familyService.getFamilyByAccount(familyAccount);
	String usertype = "";
	if (family != null ) {
		usertype = family.getLevel();
	}
	UsernamePasswordUsertypeToken token = new UsernamePasswordUsertypeToken(familyAccount, password, usertype);
	String result = "";
	if(family == null) {
		result = "usernameError";
	} else {
		try {
		    SecurityUtils.getSubject().login(token);
		    result = "success";
		}catch (UnknownAccountException e) {
		    result = "usernameError";
		}catch (IncorrectCredentialsException e) {
		    result = "passwordError";
		}
	}
	JSONObject object = new JSONObject();
	object.put("result", result);
	object.put("usertype", usertype);
	return object.toJSONString();
    }

    @RequestMapping("/login")
    public String login() {
	return "login";
    }
    
    @RequestMapping("/logout")
    public String familyLogout() {
	try {
	    SecurityUtils.getSubject().logout();
	} catch (Exception e) {
	    System.out.println("安全退出失败");
	}
	return "redirect:/login";
    }
    /**
     * http://localhost:8081/gradesign/index#
     * 主页面
     * @param request
     * @return
     */
    @RequestMapping("/index")
    public ModelAndView loginSuccess(HttpServletRequest request) {
	//菜单
	List<Menu> parentMenu = menuService.getParentMenu();
	List<Menu> childMenu = menuService.getChildMenu();
	List<Menu> menuList = new ArrayList<Menu>();
	for (Menu tempMenu : parentMenu) {
	    if (tempMenu.getMenu_id() == 4) {
		tempMenu.setChildMenus(childMenu);
	    }
	    menuList.add(tempMenu);
	}
	ModelAndView modelAndView = new ModelAndView();
	Map<String, String> map = new HashMap<String, String>();
    	map.put("familyAccount",PrincipalFormat.currentFA());
    	Family family = familyService.getFamilyByAccount(PrincipalFormat.currentFA());
    	if (family.getIconurl()=="" || family.getIconurl() == null) {
			family.setIconurl("/gradesign/familyicon/2e3f5ccd-9c26-4be2-9bd7-5178041a369ewelcome_back.jpg");
		}
    	modelAndView.addObject("family", family);
	modelAndView.setViewName("index");
	modelAndView.addObject("menuLists", menuList);
	//推送消息
	List<Message> msgList = messageService.msgPushQuery(map);
	//推送邮件
	List<Email> emailList = emailService.emailPushQuery(map);
	modelAndView.addObject("push_msg_amount",msgList.size());
	modelAndView.addObject("push_msg",msgList);
	modelAndView.addObject("push_email_amount",emailList.size());
	modelAndView.addObject("push_email",emailList);
	return modelAndView;

    }

    /**
     * 获取验证码
     * 
     * @param request
     * @param response
     */
    @RequestMapping("/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
	// 生成随机字串
	String verifyCode = ValidateCode.generateVerifyCode(4);
	// 存入Session待验证
	HttpSession session = request.getSession(true);
	// 删除旧验证码
	session.removeAttribute("verifyCode");
	session.setAttribute("verifyCode", verifyCode.toLowerCase());
	// 生成图片
	int w = 100, h = 34;
	try {
	    response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
	    response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
	    response.setHeader("Cache-Control", "no-cache");
	    response.setDateHeader("Expire", 0);
	    ValidateCode.outputImage(w, h, response.getOutputStream(), verifyCode);
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }
    @RequestMapping("/404")
    public String notFound() {
	return "404";
    }
    /**
     * 验证填写验证码是否和服务器端存储验证码相同
     * 验证码框失去焦点进行验证
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/validateCode")
    public String validateCode(HttpServletRequest request) {
    	String randomcode = request.getParameter("randomcode");
    	String verifyCode = (String) request.getSession().getAttribute("verifyCode");
    	String result = "";
    	if (randomcode.equals(verifyCode)) {
    		result = "right";
		}else {
			result = "wrong";
		}
    	JSONObject object = new JSONObject();
    	object.put("result", result);
    	return object.toJSONString();
    }
    @RequestMapping("/familyInfo")
    public String familyInfo(Model model) {
    	Map<String, String> map = new HashMap<String, String>();
    	map.put("familyAccount",PrincipalFormat.currentFA());
    	Family family = familyService.getFamilyByAccount(PrincipalFormat.currentFA());
    	if (family.getIconurl()=="" || family.getIconurl() == null) {
			family.setIconurl("/gradesign/familyicon/2e3f5ccd-9c26-4be2-9bd7-5178041a369ewelcome_back.jpg");
		}
    	model.addAttribute("family", family);
	return "familyInfo";
    }
    /**
     * 获取家庭头像
     * @param response
     */
    @RequestMapping("/getfamilyicon")
    public void getFamilyIcon(HttpServletResponse response) {
	Map<String, String> map = new HashMap<String, String>();
	map.put("familyAccount", PrincipalFormat.currentFA());
	Family family = familyService.getFamilyByAccount(PrincipalFormat.currentFA());
	//实体类中使用BLOB类型获取为空，故使用Object类型
	Object iconBlob = family.getFamilyicon();
	byte[] by = null;
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	try {
	    ObjectOutputStream oos = new ObjectOutputStream(bos);
	    oos.writeObject(iconBlob);
	    oos.flush();
	    by = bos.toByteArray();
	    oos.close();
	    bos.close();
	    response.setContentType("image/JPEG");
	    response.getOutputStream().write(by);
	}catch (Exception e) {
	    e.printStackTrace();
	}

    }
}
